<template>
  <view class="user-info-container">
    <!-- 头像区域 -->
    <view class="avatar-container">
      <image :src="userInfo.avatar || '/static/logo.png'" class="avatar" @click="showAvatarSelect = true"></image>
      <text class="change-avatar">更换头像</text>
    </view>
    
    <!-- 表单区域 -->
    <view class="form-container">
      <view class="form-item">
        <text class="form-label">昵称</text>
        <input 
          v-model="userInfo.nickname" 
          class="form-input" 
          placeholder="请输入昵称" 
          maxlength="20"
        />
      </view>
      
      <view class="form-item">
        <text class="form-label">手机号</text>
        <text class="form-text">{{ userInfo.phone }}</text>
      </view>
    </view>
    
    <!-- 提交按钮 -->
    <button 
      class="submit-btn" 
      @click="saveUserInfo"
      :loading="isLoading"
      :disabled="isLoading"
    >
      保存修改
    </button>

    <!-- 头像选择弹窗 -->
    <view v-if="showAvatarSelect" class="avatar-select-modal">
      <view class="modal-content">
        <view class="modal-title">选择头像</view>
        <view class="avatar-list">
          <image 
            v-for="(avatar, idx) in avatarList" 
            :key="idx" 
            :src="avatar" 
            class="avatar-item" 
            @click="selectStaticAvatar(avatar)"
          />
        </view>
        <button class="close-btn" @click="showAvatarSelect = false">取消</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isLoading: false,
      showAvatarSelect: false,
      userInfo: {
        id: '',
        avatar: '',
        nickname: '',
        phone: ''
      },
      // 静态头像列表（对应前端static/background目录下的图片，确保路径存在）
      avatarList: [
        '/static/touxiang/t1.jpg',
        '/static/touxiang/t2.jpg',
        '/static/touxiang/t3.jpg',
        '/static/touxiang/t4.jpg',
        '/static/touxiang/t5.jpg',
		'/static/touxiang/t6.jpg',
		'/static/touxiang/t7.jpg',
		'/static/touxiang/t8.jpg',
		'/static/touxiang/t9.jpg',
		'/static/touxiang/t10.jpg',
		'/static/touxiang/t11.jpg',
		'/static/touxiang/t12.jpg'
      ],
      baseURL: 'http://localhost:8080' 
    }
  },
  onLoad() {
    // 从本地存储获取用户信息
    const storedUser = uni.getStorageSync('userInfo') || {}
    this.userInfo = { ...storedUser }
    
    // 登录状态校验
    if (!this.userInfo.id) {
      uni.showToast({ title: '请先登录', icon: 'none', duration: 1500 })
      setTimeout(() => {
        uni.navigateTo({ url: '/pages/login' }) // 确保登录页路径正确
      }, 1000)
    }
  },
  methods: {
    // 选择静态头像
    selectStaticAvatar(avatarPath) {
      this.userInfo.avatar = avatarPath
      uni.setStorageSync('userInfo', this.userInfo) // 本地缓存更新
      this.showAvatarSelect = false
      uni.showToast({ title: '头像选择成功', icon: 'success', duration: 1500 })
    },
    
    // 保存用户信息（修复语法错误 + 兼容uni.$http可能未定义的问题）
    async saveUserInfo() {
      // 表单验证
      if (!this.userInfo.nickname.trim()) {
        return uni.showToast({ title: '请输入昵称', icon: 'none', duration: 1500 })
      }
      if (this.userInfo.nickname.length > 20) {
        return uni.showToast({ title: '昵称不能超过20个字符', icon: 'none', duration: 1500 })
      }
      if (!this.userInfo.id) {
        return uni.showToast({ title: '用户信息异常', icon: 'none', duration: 1500 })
      }
    
      try {
        this.isLoading = true // 按钮加载状态（与原逻辑保持一致）
        uni.showLoading({ title: '保存中...' })
        
        // 优先用uni.request（避免uni.$http未配置的问题，与找回密码页逻辑兼容）
        const res = await new Promise((resolve, reject) => {
          uni.request({
            url: this.baseURL + '/user/update', // 完整请求地址
            method: 'POST',
            data: this.userInfo, // 提交用户信息（含静态头像路径）
            timeout: 30000, // 30秒超时
            success: resolve,
            fail: reject
          })
        })
        
        uni.hideLoading()
        this.isLoading = false
        
        // 处理响应
        if (res.statusCode !== 200) {
          throw new Error(`HTTP错误：${res.statusCode}`)
        }
        if (res.data.code === 200) {
          uni.setStorageSync('userInfo', this.userInfo)
          uni.showToast({ title: '保存成功', duration: 1500 })
          setTimeout(() => uni.navigateBack(), 1000)
        } else {
          uni.showToast({ 
            title: res.data.msg || '保存失败', 
            icon: 'none',
            duration: 1500
          })
        }
      } catch (err) {
        uni.hideLoading()
        this.isLoading = false
        console.error('保存失败：', err)
        uni.showToast({ 
          title: '网络连接失败，请稍后重试', 
          icon: 'none',
          duration: 1500
        })
      }
    }
  } // 修复：闭合methods对象
} // 修复：闭合export default对象
</script>

<style scoped>
.user-info-container {
  padding: 50rpx 30rpx;
  background-color: #fff;
  min-height: 100vh;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 60rpx;
  padding: 20rpx 0;
}

.avatar {
  width: 200rpx;
  height: 200rpx;
  border-radius: 100rpx;
  margin-bottom: 20rpx;
  border: 1px solid #eee;
}

.change-avatar {
  font-size: 28rpx;
  color: #1890ff;
  margin-top: 10rpx;
}

.form-container {
  margin-bottom: 60rpx;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  height: 100rpx;
  border-bottom: 1px solid #f5f5f5;
}

.form-label {
  width: 140rpx;
  font-size: 32rpx;
  color: #333;
}

.form-input, .form-text {
  flex: 1;
  font-size: 32rpx;
  height: 100%;
  line-height: 100rpx;
  padding: 0 20rpx;
  color: #333;
}

.form-text {
  color: #666;
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 32rpx;
  background-color: #52c41a;
  color: #fff;
  border-radius: 45rpx;
  margin-top: 60rpx;
}

/* 头像选择弹窗样式 */
.avatar-select-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.modal-content {
  width: 80%;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  display: flex;
  flex-direction: column;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
  color: #333;
}

.avatar-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  justify-content: center;
  margin-bottom: 40rpx;
}

.avatar-item {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  border: 2px solid transparent;
}

.avatar-item:active {
  border-color: #1890ff;
}

.close-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
  background-color: #f5f5f5;
  color: #666;
  border-radius: 10rpx;
}
</style>